package com.ssy.lingxi.product.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.product.CommodityStatusEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.model.vo.PageVO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.component.redis.service.IRedisStringUtils;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberInnerControllerFeign;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignQueryVO;
import com.ssy.lingxi.product.api.model.request.*;
import com.ssy.lingxi.product.api.model.request.commodity.CommodityAttributeRequest;
import com.ssy.lingxi.product.api.model.request.price.PriceDeleteRequest;
import com.ssy.lingxi.product.api.model.request.price.PriceUpdateRequest;
import com.ssy.lingxi.product.api.model.response.*;
import com.ssy.lingxi.product.api.model.response.commodity.GoodsIdAndFirstCategoryIdResponse;
import com.ssy.lingxi.product.common.enums.*;
import com.ssy.lingxi.product.entity.*;
import com.ssy.lingxi.product.entity.commodity.CommodityUnitPriceAndPic;
import com.ssy.lingxi.product.entity.customer.CustomerAttribute;
import com.ssy.lingxi.product.entity.customer.CustomerAttributeValue;
import com.ssy.lingxi.product.entity.customer.CustomerCategory;
import com.ssy.lingxi.product.entity.material.MaterInnerLog;
import com.ssy.lingxi.product.entity.material.MaterialAttribute;
import com.ssy.lingxi.product.entity.material.MaterialGroup;
import com.ssy.lingxi.product.model.dto.material.MaterialProcessDTO;
import com.ssy.lingxi.product.model.request.MaterialExamineRequest;
import com.ssy.lingxi.product.model.resp.MaterInnerLogResponse;
import com.ssy.lingxi.product.model.resp.MaterialInnerStatusResponse;
import com.ssy.lingxi.product.repository.BrandRepository;
import com.ssy.lingxi.product.repository.GoodsRepository;
import com.ssy.lingxi.product.repository.commodity.CommodityUnitPriceAndPicRepository;
import com.ssy.lingxi.product.repository.customer.CustomerAttributeRepository;
import com.ssy.lingxi.product.repository.customer.CustomerAttributeValueRepository;
import com.ssy.lingxi.product.repository.customer.CustomerCategoryRepository;
import com.ssy.lingxi.product.repository.material.GoodsSupplyListRepository;
import com.ssy.lingxi.product.repository.material.MaterInnerLogRepository;
import com.ssy.lingxi.product.repository.material.MaterialAttributeRepository;
import com.ssy.lingxi.product.repository.material.MaterialGroupRepository;
import com.ssy.lingxi.product.service.IGoodsService;
import com.ssy.lingxi.product.service.material.IMaterialProcessService;
import com.ssy.lingxi.product.service.price.IPriceManagementService;
import com.ssy.lingxi.report.api.enums.CommonBooleanEnum;
import com.ssy.lingxi.workflow.api.feign.ProcessFeign;
import com.ssy.lingxi.workflow.api.model.vo.request.InternalProcessQueryVO;
import com.ssy.lingxi.workflow.api.model.vo.request.TaskExecuteVO;
import com.ssy.lingxi.workflow.api.model.vo.request.TaskStartVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleProcessDefVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskCompleteVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;


/**
 * 货品实现类
 *
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/6/22
 */
@Service
public class GoodsServiceImpl implements IGoodsService {

    @Resource
    private GoodsRepository goodsRepository;
    @Resource
    private CustomerCategoryRepository customerCategoryRepository;
    @Resource
    private BrandRepository brandRepository;
    @Resource
    private CommodityUnitPriceAndPicRepository unitPriceAndPicRepository;
    @Resource
    private IRedisStringUtils redisStringUtils;
    @Resource
    private MaterialAttributeRepository materialAttributeRepository;
    @Resource
    private MaterialGroupRepository materialGroupRepository;
    @Resource
    private CustomerAttributeRepository customerAttributeRepository;
    @Resource
    private CustomerAttributeValueRepository customerAttributeValueRepository;
    @Resource
    private GoodsSupplyListRepository goodsSupplyListRepository;
    @Resource
    private MaterInnerLogRepository materInnerLogRepository;
    @Resource
    private ProcessFeign taskExecuteControllerFeign;
    @Resource
    private IPriceManagementService priceManagementService;
    @Resource
    private IMaterialProcessService materialProcessService;
    @Resource
    private MemberInnerControllerFeign memberInnerControllerFeign;
    @Resource
    private JPAQueryFactory jpaQueryFactory;

    /**
     * 物料管理-物料查询-获取物料工作流程全部状态
     *
     * @return 操作结果
     */
    @Override
    public List<MaterialInnerStatusResponse> getInnerStatus() {
        List<MaterialInnerStatusResponse> innerStatus = MaterialsAddInternalStatusEnum.getInnerStatus();
        innerStatus.addAll(MaterialsChangeOrEnableInternalStatusEnum.getInnerStatus());
        return new ArrayList<>(innerStatus).stream().distinct().sorted(Comparator.comparing(MaterialInnerStatusResponse::getStatus)).collect(Collectors.toList());
    }

    /**
     * 物料管理-物料查询-详情-内部单据流转记录
     *
     * @param goodsId 物料id
     * @return 操作结果
     */
    @Override
    public List<MaterInnerLogResponse> getMaterInnerLogList(Long goodsId) {
        List<MaterInnerLog> materInnerLogs = materInnerLogRepository.findByGoodsId(goodsId);
        if (CollectionUtils.isEmpty(materInnerLogs)) {
            return new ArrayList<>();
        }
        return materInnerLogs.stream().map(materInnerLog -> {
            MaterInnerLogResponse response = new MaterInnerLogResponse();
            BeanUtils.copyProperties(materInnerLog, response);
            response.setState(
                    MaterialsAddInternalStatusEnum.FAILED_TO_PASS_THE_SECONDARY_AUDIT.getCode() > materInnerLog.getState()
                            ? MaterialsAddInternalStatusEnum.getMessage(materInnerLog.getState())
                            : MaterialsChangeOrEnableInternalStatusEnum.getMessage(materInnerLog.getState()));
            return response;
        }).sorted(Comparator.comparingLong(MaterInnerLogResponse::getId)).collect(Collectors.toList());
    }

    /**
     * 物料管理-物料查询-列表
     *
     * @param sysUser           当前登录用户
     * @param pageVO            分页实体
     * @param goodsQueryRequest 货品查询类
     * @return 操作结果
     */
    @Override
    public Page<Goods> getMaterialList(UserLoginCacheDTO sysUser, PageVO pageVO, GoodsQueryRequest goodsQueryRequest) {
        return getGoodsListCommon(sysUser, pageVO, goodsQueryRequest);
    }

    /**
     * 冻结物料
     *
     * @param sysUser                  当前登录用户
     * @param goodsFreezeEnableRequest 请求参数
     * @return 操作结果
     */
    @Transactional
    @Override
    public String freezeGoods(UserLoginCacheDTO sysUser, GoodsFreezeEnableRequest goodsFreezeEnableRequest) {
        Goods goods = goodsRepository.findByMemberIdAndMemberRoleIdAndId(sysUser.getMemberId(), sysUser.getMemberRoleId(), goodsFreezeEnableRequest.getGoodsId());
        if (ObjectUtils.isEmpty(goods)) {
            throw new BusinessException(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
        }
        if (!MaterialsAddInternalStatusEnum.CONFIRMED.getCode().equals(goods.getInteriorState()) && !MaterialsAddInternalStatusEnum.CONFIRMED.getCode().equals(goods.getExternalState())) {
            throw new BusinessException(ResponseCode.PRODUCT_INTERNAL_STATUS_IS_OK);
        }
        goods.setInteriorState(goodsFreezeEnableRequest.getStatus());
        goods.setExternalState(goodsFreezeEnableRequest.getStatus());
        //保存操作日志
        saveMaterialInnerLog(sysUser, goods.getId(), MaterialsAddInternalStatusEnum.FROZEN.getCode(), MaterialsAddInternalStatusEnum.FROZEN.getCode(), MaterialsAddInternalStatusEnum.FROZEN.getOperational(), goodsFreezeEnableRequest.getFreezeReason());
        goodsRepository.saveAndFlush(goods);
        return Wrapper.success().getMessage();
    }

    /**
     * 启用物料
     *
     * @param sysUser                  当前登录用户
     * @param goodsFreezeEnableRequest 请求参数
     * @return 操作结果
     */
    @Transactional
    @Override
    public String enableGoods(UserLoginCacheDTO sysUser, GoodsFreezeEnableRequest goodsFreezeEnableRequest) {
        Goods goods = goodsRepository.findByMemberIdAndMemberRoleIdAndId(sysUser.getMemberId(), sysUser.getMemberRoleId(), goodsFreezeEnableRequest.getGoodsId());
        if (ObjectUtils.isEmpty(goods)) {
            throw new BusinessException(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
        }
        if (!MaterialsAddInternalStatusEnum.FROZEN.getCode().equals(goods.getInteriorState())) {
            throw new BusinessException(ResponseCode.PRODUCT_INTERNAL_STATUS_IS_FREEZE);
        }
        //动态获取工作流任务id
        Wrapper<MaterialProcessDTO> wrapper = materialProcessService.getMaterialProcessByMemberIdAndRoleIdAndMaterialGroupIdAndMaterialIdAndProcessType(sysUser.getMemberId(), sysUser.getMemberRoleId(), goods.getMaterialGroup() != null ? goods.getMaterialGroup().getId() : null, goods.getId(), MaterialProcessTypeEnum.CHANGE_OR_ENABLE.getCode());
        if (wrapper.getCode() != Wrapper.success().getCode()) {
            throw new BusinessException(wrapper.getCode(), wrapper.getMessage());
        }
        goods.setChange(true);//标记为变更/启用
        goods.setExternalState(MaterialsChangeOrEnableInternalStatusEnum.PENDING_SUBMISSION.getCode());
        goods.setInteriorState(CheckStatusEnum.DEFAULT.getCode());
        //记录日志
        saveMaterialInnerLog(sysUser, goods.getId(), MaterialsChangeOrEnableInternalStatusEnum.PENDING_SUBMISSION.getCode(), MaterialsChangeOrEnableInternalStatusEnum.CONFIRMED.getCode(), MaterialsChangeOrEnableInternalStatusEnum.getOperational(MaterialsChangeOrEnableInternalStatusEnum.PENDING_SUBMISSION.getCode()), "");
        goodsRepository.saveAndFlush(goods);
        return Wrapper.success().getMessage();
    }

    /**
     * 批量冻结物料
     *
     * @param sysUser                       当前登录用户
     * @param goodsFreezeEnableBatchRequest 请求参数
     * @return 操作结果
     */
    @Override
    public String freezeGoodsBatch(UserLoginCacheDTO sysUser, GoodsFreezeEnableBatchRequest goodsFreezeEnableBatchRequest) {
        List<Goods> goodsList = goodsRepository.findByMemberIdAndMemberRoleIdAndIdIn(sysUser.getMemberId(), sysUser.getMemberRoleId(), goodsFreezeEnableBatchRequest.getGoodsId());
        if (goodsList.size() <= 0) {
            throw new BusinessException(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
        }
        //物料内部状态要全为已确认
        boolean confirmed = goodsList.stream().anyMatch(g -> !MaterialsAddInternalStatusEnum.CONFIRMED.getCode().equals(g.getInteriorState()) && !MaterialsAddInternalStatusEnum.CONFIRMED.getCode().equals(g.getExternalState()));
        if (confirmed) {
            throw new BusinessException(ResponseCode.PRODUCT_INTERNAL_STATUS_IS_OK);
        }
        goodsList.forEach(goods -> {
            goods.setInteriorState(goodsFreezeEnableBatchRequest.getStatus());
            goods.setExternalState(goodsFreezeEnableBatchRequest.getStatus());
        });
        goodsRepository.saveAll(goodsList);
        goodsRepository.flush();
        //批量保存日志
        saveMaterialInnerLogBatch(goodsList, sysUser, goodsFreezeEnableBatchRequest.getFreezeReason());
        materInnerLogRepository.flush();
        return Wrapper.success().getMessage();
    }

    /**
     * 批量保存日志
     *
     * @param goodsList 货品集合
     */
    private void saveMaterialInnerLogBatch(List<Goods> goodsList, UserLoginCacheDTO sysUser, String freezeReason) {
        List<MaterInnerLog> materInnerLogs = goodsList.stream().map(goods -> {
            MaterInnerLog innerLog = new MaterInnerLog();
            innerLog.setGoodsId(goods.getId());
            innerLog.setRoleName(sysUser.getUserName());
            innerLog.setMemberRoleId(sysUser.getMemberRoleId());
            innerLog.setMemberId(sysUser.getMemberId());
            innerLog.setState(goods.getInteriorState());
            innerLog.setStep(goods.getInteriorNextStep());
            innerLog.setOperation(freezeReason);
            innerLog.setAuditOpinion("");
            innerLog.setDepartment(sysUser.getUserOrgName());
            innerLog.setPosition(sysUser.getUserJobTitle());
            return innerLog;
        }).collect(Collectors.toList());
        materInnerLogRepository.saveAll(materInnerLogs);
    }

    /**
     * 批量启用物料
     *
     * @param sysUser                       当前登录用户
     * @param goodsFreezeEnableBatchRequest 请求参数
     * @return 操作结果
     */
    @Transactional
    @Override
    public String enableGoodsBatch(UserLoginCacheDTO sysUser, GoodsFreezeEnableBatchRequest goodsFreezeEnableBatchRequest) {
        List<Goods> goodsList = goodsRepository.findByMemberIdAndMemberRoleIdAndIdIn(sysUser.getMemberId(), sysUser.getMemberRoleId(), goodsFreezeEnableBatchRequest.getGoodsId());
        if (goodsList.size() <= 0) {
            throw new BusinessException(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
        }
        //物料内部状态要全为已冻结
        boolean anyMatch = goodsList.stream().anyMatch(g -> !MaterialsAddInternalStatusEnum.FROZEN.getCode().equals(g.getInteriorState()));
        if (anyMatch) {
            throw new BusinessException(ResponseCode.PRODUCT_INTERNAL_STATUS_IS_FREEZE);
        }
        goodsList.forEach(goods -> {
            //动态获取工作流任务id
            Wrapper<MaterialProcessDTO> wrapper = materialProcessService.getMaterialProcessByMemberIdAndRoleIdAndMaterialGroupIdAndMaterialIdAndProcessType(sysUser.getMemberId(), sysUser.getMemberRoleId(), goods.getMaterialGroup() != null ? goods.getMaterialGroup().getId() : null, goods.getId(), MaterialProcessTypeEnum.CHANGE_OR_ENABLE.getCode());
            if (wrapper.getCode() != Wrapper.success().getCode()) {
                throw new BusinessException(wrapper.getCode(), wrapper.getMessage());
            }
            goods.setChange(true);//标记为变更/启用
            goods.setExternalState(MaterialsChangeOrEnableInternalStatusEnum.PENDING_SUBMISSION.getCode());
            goods.setInteriorState(CheckStatusEnum.DEFAULT.getCode());
            //记录日志
            saveMaterialInnerLog(sysUser, goods.getId(), MaterialsChangeOrEnableInternalStatusEnum.PENDING_SUBMISSION.getCode(), MaterialsChangeOrEnableInternalStatusEnum.CONFIRMED.getCode(), MaterialsChangeOrEnableInternalStatusEnum.getOperational(MaterialsChangeOrEnableInternalStatusEnum.PENDING_SUBMISSION.getCode()), "");
            goodsRepository.saveAndFlush(goods);
        });
        return Wrapper.success().getMessage();
    }

    /**
     * 物料管理-物料查询-物料清单-列表
     *
     * @param request 请求参数
     * @return 操作结果
     */
    @Override
    public List<GoodsSupplyList> getGoodsSourceList(SimpleIdRequest request) {
        //根据时间倒序
        return goodsSupplyListRepository.findByGoodsId(request.getId()).stream().filter(Objects::nonNull)
                .sorted(Comparator.comparing(GoodsSupplyList::getCreateTime).reversed())
                .collect(Collectors.toList());
    }

    /**
     * 物料管理-物料查询-物料清单-提交保存
     *
     * @param request 请求参数
     * @return 操作结果
     */
    @Transactional
    @Override
    public String submitGoodsSourceList(GoodsSupplyRequest request) {
        Goods goods = goodsRepository.findById(request.getId()).orElse(null);
        if (goods == null) {
            throw new BusinessException(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
        }
        //先清除已有的数据
        List<GoodsSupplyList> goodsSupplyLists = goods.getGoodsSupplyLists();
        if (!CollectionUtils.isEmpty(goodsSupplyLists)) {
            goodsSupplyListRepository.deleteAll(goodsSupplyLists);
            goods.setGoodsSupplyLists(null);
        }
        //保存全部数据
        List<GoodsSupplyList> supplyLists = request.getList().stream().map(g -> BeanUtil.copyProperties(g, GoodsSupplyList.class)).peek(s -> s.setGoods(goods)).collect(Collectors.toList());
        goods.setGoodsSupplyLists(supplyLists);
        goodsRepository.saveAndFlush(goods);
        return Wrapper.success().getMessage();
    }

    /**
     * 查询货品列表
     *
     * @param pageVO            分页实体
     * @param goodsQueryRequest 货品查询类
     * @return 操作结果
     */
    @Override
    public Page<Goods> getGoodsList(UserLoginCacheDTO sysUser, PageVO pageVO, GoodsQueryRequest goodsQueryRequest) {
        return getGoodsListCommon(sysUser, pageVO, goodsQueryRequest);

    }

    /**
     * 查询货品列表
     *
     * @param pageVO            分页实体
     * @param goodsQueryRequest 货品查询类
     * @return 操作结果
     */
    @Override
    public Page<Goods> getToBeAddGoodsList(UserLoginCacheDTO sysUser, PageVO pageVO, GoodsQueryRequest goodsQueryRequest) {
        List<Integer> ids = goodsQueryRequest.getIds();
        ids.addAll(MaterialsAddInternalStatusEnum.getAssignCodeList());
        ids.addAll(MaterialsChangeOrEnableInternalStatusEnum.getAssignCodeList());
        return getGoodsListCommon(sysUser, pageVO, goodsQueryRequest);

    }

    /**
     * 物料管理-查询货品列表(内部状态不为冻结)
     *
     * @param sysUser           当前登录用户
     * @param pageVO            分页实体
     * @param goodsQueryRequest 货品查询类
     * @return 操作结果
     */
    @Override
    public Page<Goods> getDoesNotFreezeGoodsList(UserLoginCacheDTO sysUser, PageVO pageVO, GoodsQueryRequest goodsQueryRequest) {
        List<Integer> ids = goodsQueryRequest.getIds();
        ids.addAll(MaterialsAddInternalStatusEnum.getCodeNotZeroList());
        ids.addAll(Arrays.stream(MaterialsChangeOrEnableInternalStatusEnum.values()).map(MaterialsChangeOrEnableInternalStatusEnum::getCode).collect(Collectors.toList()));
        return getGoodsListCommon(sysUser, pageVO, goodsQueryRequest);
    }

    /**
     * 物料查询公共方法
     *
     * @param sysUser           当前登录用户
     * @param pageVO            分页参数
     * @param goodsQueryRequest 请求参数体
     */
    private Page<Goods> getGoodsListCommon(UserLoginCacheDTO sysUser, PageVO pageVO, GoodsQueryRequest goodsQueryRequest) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        goodsQueryRequest.setMemberId(sysUser.getMemberId());
        goodsQueryRequest.setMemberRoleId(sysUser.getMemberRoleId());
        Page<Goods> goodsList = goodsRepository.findAll(getSpecification(goodsQueryRequest), page);
        goodsList.stream().forEach(goods -> {
            String unit = redisStringUtils.hMGet(Constants.REDIS_KEY_UNIT, String.valueOf(goods.getUnitId()), Constants.REDIS_PLATFORM_MANAGE_INDEX);
            goods.setUnitName(StringUtils.isNotEmpty(unit) ? unit.split(Constants.TRANSFER_STR + Constants.SPLIT_STR)[0] : "");
            //设置内部状态名称
            if (goods.getExternalState() != null && goods.getExternalState() > 0) {
                goods.setInteriorStateName(MaterialsChangeOrEnableInternalStatusEnum.getMessage(goods.getExternalState()));
                goods.setInteriorState(goods.getExternalState());
            } else {
                goods.setInteriorStateName(MaterialsAddInternalStatusEnum.getMessage(goods.getInteriorState()));
            }

        });
        return goodsList;
    }

    /**
     * 查询下级供应商货品列表(采购选品)
     *
     * @param sysUser                当前登录用户
     * @param pageVO                 分页实体
     * @param goodsQueryBySubRequest 货品查询类
     * @return 操作结果
     */
    @Override
    public Page<Goods> getSubGoodsList(UserLoginCacheDTO sysUser, PageVO pageVO, GoodsQueryBySubRequest goodsQueryBySubRequest) {
        //获取下级供应商（角色类型为服务提供者）的会员Id和角色Id列表
        MemberFeignVO memberFeignVO = new MemberFeignVO();
        memberFeignVO.setMemberId(sysUser.getMemberId());
        memberFeignVO.setRoleId(sysUser.getMemberRoleId());
        Wrapper<List<MemberFeignQueryVO>> wrapper = memberInnerControllerFeign.listSubProviderLowerMembers(memberFeignVO);
        if (wrapper.getCode() != Wrapper.success().getCode()) {
            throw new BusinessException(wrapper.getCode(), wrapper.getMessage());
        }
        if (CollectionUtils.isEmpty(wrapper.getData())) {
            return new PageImpl<>(new ArrayList<>());
        }
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        Page<Goods> goodsList = goodsRepository.findAll(getSubSpecification(wrapper.getData(), goodsQueryBySubRequest), page);
        goodsList.stream().forEach(goods -> {
            String unit = redisStringUtils.hMGet(Constants.REDIS_KEY_UNIT, String.valueOf(goods.getUnitId()), Constants.REDIS_PLATFORM_MANAGE_INDEX);
            goods.setUnitName(StringUtils.isNotEmpty(unit) ? unit.split(Constants.TRANSFER_STR + Constants.SPLIT_STR)[0] : "");
        });
        return goodsList;
    }

    /**
     * 构造查询条件
     *
     * @param goodsQueryBySubRequest 查询条件请求体
     * @return 操作结果
     */
    private Specification<Goods> getSubSpecification(List<MemberFeignQueryVO> memberFeignQueryVOS, GoodsQueryBySubRequest goodsQueryBySubRequest) {
        //下级供应商信息
        return (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();
            if (!StringUtils.isEmpty(goodsQueryBySubRequest.getUserName())) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.like(root.get("userName").as(String.class), "%" + goodsQueryBySubRequest.getName() + "%"));
            }
            if (!StringUtils.isEmpty(goodsQueryBySubRequest.getName())) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.like(root.get("name").as(String.class), "%" + goodsQueryBySubRequest.getName() + "%"));
            }
            if (!StringUtils.isEmpty(goodsQueryBySubRequest.getType())) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.like(root.get("type").as(String.class), "%" + goodsQueryBySubRequest.getType() + "%"));
            }
            if (goodsQueryBySubRequest.getBrandId() != null && goodsQueryBySubRequest.getBrandId() > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("brand").as(Brand.class), goodsQueryBySubRequest.getBrandId()));
            }
            if (goodsQueryBySubRequest.getCustomerCategoryId() != null && goodsQueryBySubRequest.getCustomerCategoryId() > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("customerCategory").as(CustomerCategory.class), goodsQueryBySubRequest.getCustomerCategoryId()));
            }
            //查询条件为当前会员的下级供应商会员id和角色id
            if (!CollectionUtils.isEmpty(memberFeignQueryVOS)) {
                Predicate disjunction = criteriaBuilder.disjunction();
                for (MemberFeignQueryVO s : memberFeignQueryVOS) {
                    Predicate memberIdPre = criteriaBuilder.equal(root.get("memberId"), s.getMemberId());
                    Predicate and = criteriaBuilder.and(memberIdPre, criteriaBuilder.equal(root.get("memberRoleId"), s.getRoleId()));
                    disjunction = criteriaBuilder.or(disjunction, and);
                }
                finalConditions = criteriaBuilder.and(finalConditions, disjunction);
            }

            //内部状态为99或者外部状态为99 已确认
            Predicate interiorState = criteriaBuilder.equal(root.get("interiorState"), MaterialsAddInternalStatusEnum.CONFIRMED.getCode());
            Predicate or = criteriaBuilder.or(interiorState, criteriaBuilder.equal(root.get("externalState"), MaterialsChangeOrEnableInternalStatusEnum.CONFIRMED.getCode()));
            finalConditions = criteriaBuilder.and(finalConditions, or);

            query.orderBy(criteriaBuilder.desc(root.get("createTime")));
            return finalConditions;
        };
    }

    /**
     * 查询货品列表
     *
     * @param pageVO 分页实体
     * @param name   货品名称/货号/品牌名称
     * @return 操作结果
     */
    @Override
    public Page<Goods> getAppGoodsList(UserLoginCacheDTO sysUser, PageVO pageVO, String name) {
        Pageable page = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize());
        Page<Goods> goodsList = goodsRepository.findAll(getAppSpecification(sysUser.getMemberId(), sysUser.getMemberRoleId(), name), page);
        goodsList.stream().forEach(goods -> {
            String unit = redisStringUtils.hMGet(Constants.REDIS_KEY_UNIT, String.valueOf(goods.getUnitId()), Constants.REDIS_PLATFORM_MANAGE_INDEX);
            goods.setUnitName(StringUtils.isNotEmpty(unit) ? unit.split(Constants.TRANSFER_STR + Constants.SPLIT_STR)[0] : "");
        });
        return goodsList;
    }

    /**
     * 查询货品
     *
     * @return id
     */
    @Override
    public Goods getGoods(UserLoginCacheDTO sysUser, Long id) {
        return goodsRepository.findById(id).orElse(null);

    }

    /**
     * 添加/修改货品
     *
     * @param goodsRequest 请求参数
     * @return 操作结果
     */
    @Transactional
    @Override
    public String saveOrUpdateGoods(UserLoginCacheDTO sysUser, GoodsRequest goodsRequest) {
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        Long userId = sysUser.getUserId();
        //判断货号是否重复
        Long id = goodsRequest.getId();
        String code = goodsRequest.getCode();
        List<Goods> old_goods;
        Goods goods;
        if (id != null && id > 0) {
            goods = goodsRepository.findById(id).orElse(null);
            if (goods == null) {
                throw new BusinessException(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
            }
            //清除中间数据
            this.clearMiddleTable(goods);
            old_goods = goodsRepository.findByMemberIdAndMemberRoleIdAndCodeAndIdNot(memberId, memberRoleId, code, id);
        } else {
            goods = new Goods();
            old_goods = goodsRepository.findByMemberIdAndMemberRoleIdAndCode(memberId, memberRoleId, code);
        }
        if (!old_goods.isEmpty()) {
            throw new BusinessException(ResponseCode.PRODUCT_MATERIEL_CODE_EXIST);
        }
        //检查品类是否存在
        Long customerCategoryId = goodsRequest.getCustomerCategory().getId();
        if (customerCategoryId != null && customerCategoryId > 0) {
            CustomerCategory customerCategory = customerCategoryRepository.findById(customerCategoryId).orElse(null);
            if (customerCategory != null) {
                goods.setCustomerCategory(customerCategory);
            } else {
                throw new BusinessException(ResponseCode.PRODUCT_CATEGORY_NOT_EXIST);
            }
        } else {
            throw new BusinessException(ResponseCode.PRODUCT_CATEGORY_NOT_EXIST);
        }
        //检查品牌是否存在
        Long brandId = goodsRequest.getBrand() != null ? goodsRequest.getBrand().getId() : null;
        if (brandId != null && brandId > 0) {
            Brand currentBrand = brandRepository.findById(brandId).orElse(null);
            if (currentBrand != null) {
                //判断品牌是否审核通过
                Integer status = currentBrand.getStatus();
                if (!CommodityStatusEnum.Pass.getCode().equals(status)) {
                    throw new BusinessException(ResponseCode.PRODUCT_BRAND_NOT_PASS);
                }
                //判断是否启用
                Boolean isEnable = currentBrand.getIsEnable();
                if (!isEnable) {
                    throw new BusinessException(ResponseCode.PRODUCT_BRAND_NOT_ENABLE);
                }
                goods.setBrand(currentBrand);
            } else {
                throw new BusinessException(ResponseCode.PRODUCT_BRAND_NOT_EXIST);
            }
        }
        //检查单位是否存在并启用
        Long unitId = goodsRequest.getUnitId();
        if (unitId != null && unitId > 0) {
            String unit = redisStringUtils.hMGet(Constants.REDIS_KEY_UNIT, String.valueOf(unitId), Constants.REDIS_PLATFORM_MANAGE_INDEX);
            if (unit == null || StringUtils.isEmpty(unit)) {
                throw new BusinessException(ResponseCode.PLATFORM_MANAGE_UNIT_NOT_EXIST);
            }
            goods.setUnitId(goodsRequest.getUnitId());
        } else {
            throw new BusinessException(ResponseCode.PLATFORM_MANAGE_UNIT_NOT_EXIST);
        }
        //检查物料组是否存在
        Long materialGroupId = goodsRequest.getMaterialGroup() != null ? goodsRequest.getMaterialGroup().getId() : null;
        if (materialGroupId != null && materialGroupId > 0) {
            MaterialGroup materialGroup = materialGroupRepository.findById(materialGroupId).orElse(null);
            if (materialGroup == null) {
                throw new BusinessException(ResponseCode.MATERIAL_GROUP_NOT_EXIST);
            }
            goods.setMaterialGroup(materialGroup);
        }
        //属性校验
        List<MaterialAttribute> commodityAttributeList = new ArrayList<>();
        List<CommodityAttributeRequest> attributeRequestList = goodsRequest.getCommodityAttributeList();
        if (!CollectionUtils.isEmpty(attributeRequestList)) {
            //判断属性是否存在
            attributeRequestList.forEach(commodityAttributeRequest -> {
                MaterialAttribute materialAttribute = new MaterialAttribute();
                //判断所有会员属性是否存在
                Long commodityAttributeId = commodityAttributeRequest.getCustomerAttribute().getId();
                CustomerAttribute customerAttribute = customerAttributeRepository.findById(commodityAttributeId).orElse(null);
                if (customerAttribute != null) {
                    Boolean isEnable = customerAttribute.getIsEnable();
                    if (isEnable) {
                        materialAttribute.setCustomerAttribute(customerAttribute);
                    } else {
                        throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_NOT_ENABLE);
                    }
                } else {
                    throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_NOT_EXIST);
                }
                //判断所有会员属性值是否存在
                List<CustomerAttributeValue> customerAttributeValueList = new ArrayList<>();
                commodityAttributeRequest.getCustomerAttributeValueList().forEach(customerAttributeValueRequest -> {
                    Long customerAttributeValueId = customerAttributeValueRequest.getId();
                    if (customerAttributeValueId != null && customerAttributeValueId > 0) {
                        CustomerAttributeValue customerAttributeValue = customerAttributeValueRepository.findById(customerAttributeValueId).orElse(null);
                        if (customerAttributeValue != null) {
                            Boolean isEnable = customerAttributeValue.getIsEnable();
                            if (isEnable) {
                                customerAttributeValueList.add(customerAttributeValue);
                            } else {
                                throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_VALUE_NOT_ENABLE);
                            }
                        } else {
                            throw new BusinessException(ResponseCode.PRODUCT_ATTRIBUTE_VALUE_NOT_EXIST);
                        }
                    } else {
                        String value = customerAttributeValueRequest.getValue();
                        CustomerAttributeValue customerAttributeValue = customerAttributeValueRepository.findFirstByMemberIdAndMemberRoleIdAndValue(sysUser.getMemberId(), sysUser.getMemberRoleId(), value);
                        customerAttributeValueList.add(customerAttributeValue);
                    }
                });
                materialAttribute.setCustomerAttributeValueList(customerAttributeValueList);
                materialAttribute.setGoods(goods);
                commodityAttributeList.add(materialAttribute);
            });
            goods.setMaterialAttributeList(commodityAttributeList);
        }
        //校验物料货源清单
        GoodsSupplyListRequest goodsSupplyListRequest = goodsRequest.getGoodsSupplyListRequest();
        if (goodsSupplyListRequest != null) {
            Goods g = goodsRepository.findByMemberIdAndMemberRoleIdAndId(goodsSupplyListRequest.getMemberId(), goodsSupplyListRequest.getMemberRoleId(), goodsSupplyListRequest.getGoodsId());
            if (g != null) {
                GoodsSupplyList goodsSupplyList = BeanUtil.copyProperties(goodsSupplyListRequest, GoodsSupplyList.class);
                goodsSupplyList.setGoods(goods);
                List<GoodsSupplyList> goodsSupplyLists = goods.getGoodsSupplyLists();
                goodsSupplyLists.add(goodsSupplyList);
                goods.setGoodsSupplyLists(goodsSupplyLists);
            } else {
                throw new BusinessException(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
            }
        }
        //数据库持久化对象
        goods.setId(id);
        goods.setCode(code);
        goods.setName(goodsRequest.getName());
        goods.setType(goodsRequest.getType());
        goods.setCostPrice(goodsRequest.getCostPrice());
        goods.setGoodsPic(goodsRequest.getGoodsPic());
        goods.setUrls(goodsRequest.getUrls());
        goods.setRemake(goodsRequest.getRemark());
        goods.setMemberId(memberId);
        goods.setMemberName(sysUser.getCompany());
        goods.setMemberRoleId(memberRoleId);
        goods.setMemberRoleName(sysUser.getMemberRoleName());
        goods.setUserId(userId);
        goods.setUserName(sysUser.getUserName());
        goods.setChange(goodsRequest.getChange());
        goodsRepository.saveAndFlush(goods);
        //同时更新物料价格库信息
        PriceUpdateRequest request = new PriceUpdateRequest();
        request.setGoodsId(goods.getId());
        priceManagementService.updateGoodsPrice(request);
        //判断是开启工作流还是 变更/启用工作流
        if (goodsRequest.getChange()) {
            goods.setExternalState(MaterialsChangeOrEnableInternalStatusEnum.PENDING_SUBMISSION.getCode());
            goods.setInteriorState(CheckStatusEnum.DEFAULT.getCode());
            goodsRepository.saveAndFlush(goods);
            //保存操作日志
            saveMaterialInnerLog(sysUser, goods.getId(), MaterialsChangeOrEnableInternalStatusEnum.PENDING_SUBMISSION.getCode(), null, MaterialsChangeOrEnableInternalStatusEnum.getMessage(MaterialsChangeOrEnableInternalStatusEnum.PENDING_SUBMISSION.getCode()), goodsRequest.getChangeRemark());
        } else {
            if (!MaterialsChangeOrEnableInternalStatusEnum.getAssignCodeList().contains(goods.getExternalState())) {
                goods.setInteriorState(MaterialsAddInternalStatusEnum.TO_BE_ADDED.getCode());
                goodsRepository.saveAndFlush(goods);
                //保存操作日志
                saveMaterialInnerLog(sysUser, goods.getId(), MaterialsAddInternalStatusEnum.TO_BE_ADDED.getCode(), null, MaterialsAddInternalStatusEnum.getOperational(MaterialsAddInternalStatusEnum.TO_BE_ADDED.getCode()), "");
            } else {
                //到这个流程证明是修改审核不通过的物料
                goods.setChange(true);
                goodsRepository.saveAndFlush(goods);
            }
        }
        return ResponseCode.SUCCESS.getMessage();
    }

    /**
     * 启动工作流
     */
    public Wrapper<SimpleTaskCompleteVO> startWork(UserLoginCacheDTO sysUser, Long id, String processKey) {
        TaskStartVO processStartVO = new TaskStartVO();
        processStartVO.setMemberId(sysUser.getMemberId());
        processStartVO.setRoleId(sysUser.getMemberRoleId());
        processStartVO.setProcessKey(processKey);
        processStartVO.setDataId(id);
        return taskExecuteControllerFeign.startSimpleProcess(processStartVO);
    }

    /**
     * 执行工作流
     */
    public Wrapper<SimpleTaskCompleteVO> executeWork(Long memberId, Long memberRoleId, Long id, String processKey, String taskId, Integer agree) {
        TaskExecuteVO processStartVO = new TaskExecuteVO();
        processStartVO.setMemberId(memberId);
        processStartVO.setRoleId(memberRoleId);
        processStartVO.setProcessKey(processKey);
        processStartVO.setAgree(agree);
        processStartVO.setTaskId(taskId);
        processStartVO.setDataId(id);
        return taskExecuteControllerFeign.completeSimpleTask(processStartVO);
    }

    /**
     * 启动并执行工作流
     */
    public Wrapper<SimpleTaskCompleteVO> startSimpleProcessThenCompleteFirstTask(UserLoginCacheDTO sysUser, Long id, String processKey) {
        TaskStartVO processStartVO = new TaskStartVO();
        processStartVO.setMemberId(sysUser.getMemberId());
        processStartVO.setRoleId(sysUser.getMemberRoleId());
        processStartVO.setProcessKey(processKey);
        processStartVO.setDataId(id);
        return taskExecuteControllerFeign.startSimpleProcessThenCompleteFirstTask(processStartVO);
    }

    /**
     * 保存物料操作日志
     */
    private void saveMaterialInnerLog(UserLoginCacheDTO sysUser, Long goodsId, Integer state, Integer step, String operation, String auditOpinion) {
        MaterInnerLog innerLog = new MaterInnerLog();
        innerLog.setGoodsId(goodsId);
        innerLog.setRoleName(sysUser.getUserName());
        innerLog.setMemberRoleId(sysUser.getMemberRoleId());
        innerLog.setMemberId(sysUser.getMemberId());
        innerLog.setState(state);
        innerLog.setStep(step);
        innerLog.setOperation(operation);
        innerLog.setAuditOpinion(auditOpinion);
        innerLog.setDepartment(sysUser.getUserOrgName());
        innerLog.setPosition(sysUser.getUserJobTitle());
        innerLog.setCreateTime(System.currentTimeMillis());
        materInnerLogRepository.saveAndFlush(innerLog);
    }

    /**
     * 清除物料中间表
     *
     * @param goods 请求参数
     */
    private void clearMiddleTable(Goods goods) {
        //清除物料属性中间表
        List<MaterialAttribute> materialAttributeList = goods.getMaterialAttributeList();
        if (!CollectionUtils.isEmpty(materialAttributeList)) {
            materialAttributeRepository.deleteAll(materialAttributeList);
            goods.setMaterialAttributeList(null);
        }
    }

    /**
     * 批量删除货品/物料
     *
     * @param idList 物料id集合
     * @return 操作结果
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public String deleteBatchGoods(UserLoginCacheDTO sysUser, List<Long> idList) {
        //判断货品是否存在
        List<Goods> goodsList = goodsRepository.findByMemberIdAndMemberRoleIdAndIdIn(sysUser.getMemberId(), sysUser.getMemberRoleId(), idList);
        if (goodsList.isEmpty() || goodsList.size() != idList.size()) {
            throw new BusinessException(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
        }
        //判断商品是否引用货品
        List<CommodityUnitPriceAndPic> unitPriceAndPicList = unitPriceAndPicRepository.findByGoodsIdIn(idList);
        if (!unitPriceAndPicList.isEmpty()) {
            throw new BusinessException(ResponseCode.PRODUCT_COMMODITY_RELATION_NOT_DELETE);
        }
        //同时更新物料价格库信息
        PriceDeleteRequest request = new PriceDeleteRequest();
        request.setGoodsIds(goodsList.stream().map(Goods::getId).collect(Collectors.toList()));
        priceManagementService.deleteGoodsPrice(request);

        //删除日志
        materInnerLogRepository.deleteByGoodsIdIn(idList);
        //删除物料
        goodsRepository.deleteAll(goodsList);
        return ResponseCode.SUCCESS.getMessage();
    }

    /**
     * 通过id查询一级品类id
     *
     * @param idList 请求参数
     * @return 操作结果
     */
    @Override
    public List<GoodsIdAndFirstCategoryIdResponse> getGoodsFirstCategoryIdList(List<Long> idList) {
        List<Goods> goodsList = goodsRepository.findAllById(idList);
        return goodsList.stream().map(goods -> {
            CustomerCategory customerCategory = goods.getCustomerCategory();
            String categoryId = customerCategory.getFullId();
            if (categoryId.contains(".")) {
                categoryId = categoryId.substring(0, categoryId.indexOf("."));
            }

            GoodsIdAndFirstCategoryIdResponse response = new GoodsIdAndFirstCategoryIdResponse();
            response.setGoodsId(goods.getId());
            response.setCategoryId(Long.valueOf(categoryId));
            return response;
        }).collect(Collectors.toList());
    }

    /**
     * 物料管理-待新增物料-提交审核物料单
     *
     * @param request 请求参数
     * @param sysUser 当前登录用户
     * @return 操作结果
     */
    @Transactional
    @Override
    public Wrapper<Void> goodsSubmit(SimpleIdRequest request, UserLoginCacheDTO sysUser) {
        Goods goods = goodsRepository.findByMemberIdAndMemberRoleIdAndId(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId());
        if (ObjectUtils.isEmpty(goods)) {
            return Wrapper.fail(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
        }
        if (!(MaterialsAddInternalStatusEnum.getAssignCodeList().contains(goods.getInteriorState()) || MaterialsChangeOrEnableInternalStatusEnum.getAssignCodeList().contains(goods.getExternalState()))) {
            return Wrapper.fail(ResponseCode.PRODUCT_THE_MATERIAL_CANNOT_BE_SUBMITTED);
        }
        if (goods.getChange()) {
            //动态获取工作流任务id
            Wrapper<MaterialProcessDTO> wrapper = materialProcessService.getMaterialProcessByMemberIdAndRoleIdAndMaterialGroupIdAndMaterialIdAndProcessType(sysUser.getMemberId(), sysUser.getMemberRoleId(), goods.getMaterialGroup() != null ? goods.getMaterialGroup().getId() : null, goods.getId(), MaterialProcessTypeEnum.CHANGE_OR_ENABLE.getCode());
            if (wrapper.getCode() != Wrapper.success().getCode()) {
                throw new BusinessException(wrapper.getCode(), wrapper.getMessage());
            }
            String processKey = wrapper.getData().getProcessKey();
            // 变更/启用工作流
            // 开启并执行工作流
            Wrapper<SimpleTaskCompleteVO> taskResult = startSimpleProcessThenCompleteFirstTask(sysUser, goods.getId(), processKey);
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                throw new BusinessException(taskResult.getCode(), taskResult.getMessage());
            }
            //更新流程步骤
            goods.setProcessKey(processKey);
            goods.setExternalTaskId(taskResult.getData().getTaskId());
            goods.setExternalState(taskResult.getData().getStatus());
            goods.setExternalNextStep(taskResult.getData().getStep());
            goods.setInteriorState(CheckStatusEnum.DEFAULT.getCode());
            goodsRepository.saveAndFlush(goods);
            //日志记录
            saveMaterialInnerLog(sysUser, goods.getId(), taskResult.getData().getStatus(), taskResult.getData().getStep(), MaterialsChangeOrEnableInternalStatusEnum.getMessage(taskResult.getData().getStep()), "");
        } else {
            //动态获取工作流任务id
            Wrapper<MaterialProcessDTO> wrapper = materialProcessService.getMaterialProcessByMemberIdAndRoleIdAndMaterialGroupIdAndMaterialIdAndProcessType(sysUser.getMemberId(), sysUser.getMemberRoleId(), goods.getMaterialGroup() != null ? goods.getMaterialGroup().getId() : null, goods.getId(), MaterialProcessTypeEnum.ADD.getCode());
            if (wrapper.getCode() != Wrapper.success().getCode()) {
                throw new BusinessException(wrapper.getCode(), wrapper.getMessage());
            }
            String processKey = wrapper.getData().getProcessKey();
            // 开启并执行工作流
            Wrapper<SimpleTaskCompleteVO> taskResult = startSimpleProcessThenCompleteFirstTask(sysUser, goods.getId(), processKey);
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                throw new BusinessException(taskResult.getCode(), taskResult.getMessage());
            }
            //保存工作流信息
            goods.setProcessKey(processKey);
            goods.setInteriorTaskId(taskResult.getData().getTaskId());
            goods.setInteriorState(taskResult.getData().getStatus());
            goods.setInteriorNextStep(taskResult.getData().getStep());
            goods.setExternalState(CheckStatusEnum.DEFAULT.getCode());
            goodsRepository.saveAndFlush(goods);
            //保存操作日志
            saveMaterialInnerLog(sysUser, goods.getId(), taskResult.getData().getStatus(), taskResult.getData().getStep(), MaterialsAddInternalStatusEnum.getMessage(taskResult.getData().getStep()), "");
        }
        return Wrapper.success();
    }

    /**
     * 物料管理-待审核物料(一级)-列表
     *
     * @param sysUser           当前登录用户
     * @param pageVO            分页参数
     * @param goodsQueryRequest 请求参数
     * @return 操作结果
     */
    @Override
    public Page<Goods> goodsExamineList1(UserLoginCacheDTO sysUser, PageVO pageVO, GoodsQueryRequest goodsQueryRequest) {
        goodsQueryRequest.setIds(Collections.singletonList(MaterialsAddInternalStatusEnum.TO_BE_REVIEWED_LEVEL_1.getCode()));
        return this.getGoodsListCommon(sysUser, pageVO, goodsQueryRequest);
    }

    /**
     * 物料管理-待审核物料(一级)-审核
     *
     * @param sysUser 当前登录用户
     * @param request 请求参数
     * @return 操作结果
     */
    @Transactional
    @Override
    public Wrapper<Void> goodsExamine1(UserLoginCacheDTO sysUser, MaterialExamineRequest request) {
        Goods goods = goodsRepository.findByMemberIdAndMemberRoleIdAndId(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId());
        if (ObjectUtils.isEmpty(goods)) {
            return Wrapper.fail(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
        }
        if (!MaterialsAddInternalStatusEnum.TO_BE_REVIEWED_LEVEL_1.getCode().equals(goods.getInteriorState())) {
            return Wrapper.fail(ResponseCode.PRODUCT_THE_MATERIAL_CANNOT_BE_SUBMITTED);
        }
        boolean isPass = CheckStatusEnum.AGREE.getCode().equals(request.getState());
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId(), goods.getProcessKey(), goods.getInteriorTaskId(), request.getState());
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }
        goods.setInteriorTaskId(taskResult.getData().getTaskId());
        goods.setInteriorState(taskResult.getData().getStatus());
        goods.setInteriorNextStep(taskResult.getData().getStep());
        saveMaterialInnerLog(sysUser, request.getId(), taskResult.getData().getStatus(), taskResult.getData().getStep(), MaterialsAddInternalStatusEnum.getMessage(taskResult.getData().getStep()), isPass ? AudiStatusEnum.AGREE.getMessage() : request.getAuditOpinion());
        goodsRepository.saveAndFlush(goods);
        return Wrapper.success();
    }

    /**
     * 物料管理-待审核物料(一级)-批量审核通过
     *
     * @param sysUser 当前登录用户
     * @param request 请求参数
     * @return 操作结果
     */
    @Transactional
    @Override
    public Wrapper<Void> goodsExamineBatch1(UserLoginCacheDTO sysUser, SimpleIdListRequest request) {
        List<Goods> goods = goodsRepository.findByMemberIdAndMemberRoleIdAndIdIn(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getIdList());
        if (CollectionUtils.isEmpty(goods)) {
            return Wrapper.fail(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
        }
        for (Goods good : goods) {
            if (!MaterialsAddInternalStatusEnum.TO_BE_REVIEWED_LEVEL_1.getCode().equals(good.getInteriorState())) {
                return Wrapper.fail(ResponseCode.PRODUCT_THE_MATERIAL_CANNOT_BE_SUBMITTED);
            }
            Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), good.getId(), good.getProcessKey(), good.getInteriorTaskId(), AudiStatusEnum.AGREE.getCode());
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
            }
            good.setInteriorTaskId(taskResult.getData().getTaskId());
            good.setInteriorState(taskResult.getData().getStatus());
            good.setInteriorNextStep(taskResult.getData().getStep());
            saveMaterialInnerLog(sysUser, good.getId(), taskResult.getData().getStatus(), taskResult.getData().getStep(), MaterialsAddInternalStatusEnum.getMessage(taskResult.getData().getStep()), "");
        }
        goodsRepository.saveAll(goods);
        goodsRepository.flush();
        return Wrapper.success();
    }

    /**
     * 物料管理-待审核物料(二级)-列表
     *
     * @param sysUser           当前登录用户
     * @param pageVO            分页参数
     * @param goodsQueryRequest 请求参数
     * @return 操作结果
     */
    @Override
    public Page<Goods> goodsExamineList2(UserLoginCacheDTO sysUser, PageVO pageVO, GoodsQueryRequest goodsQueryRequest) {
        goodsQueryRequest.setIds(Collections.singletonList(MaterialsAddInternalStatusEnum.TO_BE_REVIEWED_LEVEL_2.getCode()));
        return this.getGoodsListCommon(sysUser, pageVO, goodsQueryRequest);
    }

    /**
     * 物料管理-待审核物料(二级)-审核
     *
     * @param sysUser 当前登录用户
     * @param request 请求参数
     * @return 操作结果
     */
    @Transactional
    @Override
    public Wrapper<Void> goodsExamine2(UserLoginCacheDTO sysUser, MaterialExamineRequest request) {
        Goods goods = goodsRepository.findByMemberIdAndMemberRoleIdAndId(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId());
        if (ObjectUtils.isEmpty(goods)) {
            return Wrapper.fail(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
        }
        if (!MaterialsAddInternalStatusEnum.TO_BE_REVIEWED_LEVEL_2.getCode().equals(goods.getInteriorState())) {
            return Wrapper.fail(ResponseCode.PRODUCT_THE_MATERIAL_CANNOT_BE_SUBMITTED);
        }
        boolean isPass = AudiStatusEnum.AGREE.getCode().equals(request.getState());
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId(), goods.getProcessKey(), goods.getInteriorTaskId(), request.getState());
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }
        goods.setInteriorTaskId(taskResult.getData().getTaskId());
        goods.setInteriorState(taskResult.getData().getStatus());
        goods.setInteriorNextStep(taskResult.getData().getStep());
        saveMaterialInnerLog(sysUser, request.getId(), taskResult.getData().getStatus(), taskResult.getData().getStep(), MaterialsAddInternalStatusEnum.getMessage(taskResult.getData().getStep()), isPass ? AudiStatusEnum.AGREE.getMessage() : request.getAuditOpinion());
        goodsRepository.saveAndFlush(goods);
        return Wrapper.success();
    }

    /**
     * 物料管理-待审核物料(二级)-批量审核通过
     *
     * @param sysUser 当前登录用户
     * @param request 请求参数
     * @return 操作结果
     */
    @Transactional
    @Override
    public Wrapper<Void> goodsExamineBatch2(UserLoginCacheDTO sysUser, SimpleIdListRequest request) {
        List<Goods> goods = goodsRepository.findByMemberIdAndMemberRoleIdAndIdIn(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getIdList());
        if (CollectionUtils.isEmpty(goods)) {
            return Wrapper.fail(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
        }
        for (Goods good : goods) {
            if (!MaterialsAddInternalStatusEnum.TO_BE_REVIEWED_LEVEL_2.getCode().equals(good.getInteriorState())) {
                return Wrapper.fail(ResponseCode.PRODUCT_THE_MATERIAL_CANNOT_BE_SUBMITTED);
            }
            Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), good.getId(), good.getProcessKey(), good.getInteriorTaskId(), AudiStatusEnum.AGREE.getCode());
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
            }
            good.setInteriorTaskId(taskResult.getData().getTaskId());
            good.setInteriorState(taskResult.getData().getStatus());
            good.setInteriorNextStep(taskResult.getData().getStep());
            saveMaterialInnerLog(sysUser, good.getId(), taskResult.getData().getStatus(), taskResult.getData().getStep(), MaterialsAddInternalStatusEnum.getMessage(taskResult.getData().getStep()), "");
        }
        goodsRepository.saveAll(goods);
        goodsRepository.flush();
        return Wrapper.success();
    }

    /**
     * 物料管理-待审核物料变更(一级)-列表
     *
     * @param sysUser           当前登录用户
     * @param pageVO            分页参数
     * @param goodsQueryRequest 请求参数
     * @return 操作结果
     */
    @Override
    public Page<Goods> goodsExamineChangeList1(UserLoginCacheDTO sysUser, PageVO pageVO, GoodsQueryRequest goodsQueryRequest) {
        goodsQueryRequest.setIds(Collections.singletonList(MaterialsChangeOrEnableInternalStatusEnum.TO_BE_REVIEWED_LEVEL_1.getCode()));
        return this.getGoodsListCommon(sysUser, pageVO, goodsQueryRequest);
    }

    /**
     * 物料管理-待审核物料变更(一级)-审核
     *
     * @param sysUser 当前登录用户
     * @param request 请求参数
     * @return 操作结果
     */
    @Transactional
    @Override
    public Wrapper<Void> goodsExamineChange1(UserLoginCacheDTO sysUser, MaterialExamineRequest request) {
        Goods goods = goodsRepository.findByMemberIdAndMemberRoleIdAndId(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId());
        if (ObjectUtils.isEmpty(goods)) {
            return Wrapper.fail(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
        }
        if (!MaterialsChangeOrEnableInternalStatusEnum.TO_BE_REVIEWED_LEVEL_1.getCode().equals(goods.getExternalState())) {
            return Wrapper.fail(ResponseCode.PRODUCT_THE_MATERIAL_CANNOT_BE_SUBMITTED);
        }
        boolean isPass = AudiStatusEnum.AGREE.getCode().equals(request.getState());
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId(), goods.getProcessKey(), goods.getExternalTaskId(), request.getState());
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }
        goods.setExternalTaskId(taskResult.getData().getTaskId());
        goods.setExternalState(taskResult.getData().getStatus());
        goods.setExternalNextStep(taskResult.getData().getStep());
        saveMaterialInnerLog(sysUser, request.getId(), taskResult.getData().getStatus(), taskResult.getData().getStep(), MaterialsChangeOrEnableInternalStatusEnum.getMessage(taskResult.getData().getStep()), isPass ? AudiStatusEnum.AGREE.getMessage() : request.getAuditOpinion());
        goodsRepository.saveAndFlush(goods);
        return Wrapper.success();
    }

    /**
     * 物料管理-待审核物料变更(一级)-批量审核通过
     *
     * @param sysUser 当前登录用户
     * @param request 请求参数
     * @return 操作结果
     */
    @Transactional
    @Override
    public Wrapper<Void> goodsExamineChangeBatch1(UserLoginCacheDTO sysUser, SimpleIdListRequest request) {
        List<Goods> goods = goodsRepository.findByMemberIdAndMemberRoleIdAndIdIn(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getIdList());
        if (CollectionUtils.isEmpty(goods)) {
            return Wrapper.fail(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
        }
        for (Goods good : goods) {
            if (!MaterialsChangeOrEnableInternalStatusEnum.TO_BE_REVIEWED_LEVEL_1.getCode().equals(good.getExternalState())) {
                return Wrapper.fail(ResponseCode.PRODUCT_THE_MATERIAL_CANNOT_BE_SUBMITTED);
            }
            Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), good.getId(), good.getProcessKey(), good.getExternalTaskId(), CheckStatusEnum.AGREE.getCode());
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
            }

            good.setExternalTaskId(taskResult.getData().getTaskId());
            good.setExternalState(taskResult.getData().getStatus());
            good.setExternalNextStep(taskResult.getData().getStep());
            saveMaterialInnerLog(sysUser, good.getId(), taskResult.getData().getStatus(), taskResult.getData().getStep(), MaterialsChangeOrEnableInternalStatusEnum.getMessage(taskResult.getData().getStep()), "");
        }
        goodsRepository.saveAll(goods);
        goodsRepository.flush();
        return Wrapper.success();
    }

    /**
     * 物料管理-待审核物料变更(二级)-列表
     *
     * @param sysUser           当前登录用户
     * @param pageVO            分页参数
     * @param goodsQueryRequest 请求参数
     * @return 操作结果
     */
    @Override
    public Page<Goods> goodsExamineChangeList2(UserLoginCacheDTO sysUser, PageVO pageVO, GoodsQueryRequest goodsQueryRequest) {
        goodsQueryRequest.setIds(Collections.singletonList(MaterialsChangeOrEnableInternalStatusEnum.TO_BE_REVIEWED_LEVEL_2.getCode()));
        return this.getGoodsListCommon(sysUser, pageVO, goodsQueryRequest);
    }

    /**
     * 物料管理-待审核物料变更(二级)-审核
     *
     * @param sysUser 当前登录用户
     * @param request 请求参数
     * @return 操作结果
     */
    @Transactional
    @Override
    public Wrapper<Void> goodsExamineChange2(UserLoginCacheDTO sysUser, MaterialExamineRequest request) {
        Goods goods = goodsRepository.findByMemberIdAndMemberRoleIdAndId(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId());
        if (ObjectUtils.isEmpty(goods)) {
            return Wrapper.fail(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
        }
        if (!MaterialsChangeOrEnableInternalStatusEnum.TO_BE_REVIEWED_LEVEL_2.getCode().equals(goods.getExternalState())) {
            return Wrapper.fail(ResponseCode.PRODUCT_THE_MATERIAL_CANNOT_BE_SUBMITTED);
        }
        boolean isPass = AudiStatusEnum.AGREE.getCode().equals(request.getState());
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId(), goods.getProcessKey(), goods.getExternalTaskId(), request.getState());
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
        }
        goods.setExternalTaskId(taskResult.getData().getTaskId());
        goods.setExternalState(taskResult.getData().getStatus());
        goods.setExternalNextStep(taskResult.getData().getStep());
        saveMaterialInnerLog(sysUser, request.getId(), taskResult.getData().getStatus(), taskResult.getData().getStep(), MaterialsChangeOrEnableInternalStatusEnum.getMessage(taskResult.getData().getStep()), isPass ? AudiStatusEnum.AGREE.getMessage() : request.getAuditOpinion());
        goodsRepository.saveAndFlush(goods);
        return Wrapper.success();
    }

    /**
     * 物料管理-待审核物料变更(二级)-批量审核通过
     *
     * @param sysUser 当前登录用户
     * @param request 请求参数
     * @return 操作结果
     */
    @Transactional
    @Override
    public Wrapper<Void> goodsExamineChangeBatch2(UserLoginCacheDTO sysUser, SimpleIdListRequest request) {
        List<Goods> goods = goodsRepository.findByMemberIdAndMemberRoleIdAndIdIn(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getIdList());
        if (CollectionUtils.isEmpty(goods)) {
            return Wrapper.fail(ResponseCode.PRODUCT_GOODS_NOT_EXIST);
        }
        for (Goods good : goods) {
            if (!MaterialsChangeOrEnableInternalStatusEnum.TO_BE_REVIEWED_LEVEL_2.getCode().equals(good.getExternalState())) {
                return Wrapper.fail(ResponseCode.PRODUCT_THE_MATERIAL_CANNOT_BE_SUBMITTED);
            }
            Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), good.getId(), good.getProcessKey(), good.getExternalTaskId(), AudiStatusEnum.AGREE.getCode());
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                return Wrapper.fail(taskResult.getCode(), taskResult.getMessage());
            }
            good.setExternalTaskId(taskResult.getData().getTaskId());
            good.setExternalState(taskResult.getData().getStatus());
            good.setExternalNextStep(taskResult.getData().getStep());
            saveMaterialInnerLog(sysUser, good.getId(), taskResult.getData().getStatus(), taskResult.getData().getStep(), MaterialsChangeOrEnableInternalStatusEnum.getMessage(taskResult.getData().getStep()), "");
        }
        goodsRepository.saveAll(goods);
        goodsRepository.flush();
        return Wrapper.success();
    }

    /**
     * 构建查询条件
     *
     * @param goodsQueryRequest 请求参数
     * @return 操作结果
     */
    private Specification<Goods> getSpecification(GoodsQueryRequest goodsQueryRequest) {
        return (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();
            if (!StringUtils.isEmpty(goodsQueryRequest.getName())) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.like(root.get("name").as(String.class), "%" + goodsQueryRequest.getName() + "%"));
            }
            if (!StringUtils.isEmpty(goodsQueryRequest.getCode())) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.like(root.get("code").as(String.class), "%" + goodsQueryRequest.getCode() + "%"));
            }
            if (!StringUtils.isEmpty(goodsQueryRequest.getBatch())) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.like(root.get("batch").as(String.class), "%" + goodsQueryRequest.getBatch() + "%"));
            }
            if (!StringUtils.isEmpty(goodsQueryRequest.getType())) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.like(root.get("type").as(String.class), "%" + goodsQueryRequest.getType() + "%"));
            }
            if (goodsQueryRequest.getBrandId() != null && goodsQueryRequest.getBrandId() > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("brand").as(Brand.class), goodsQueryRequest.getBrandId()));
            }
            //物料组筛选
            if (goodsQueryRequest.getMaterialGroupId() != null && goodsQueryRequest.getMaterialGroupId() > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("materialGroup").as(MaterialGroup.class), goodsQueryRequest.getMaterialGroupId()));
            }
            if (goodsQueryRequest.getMemberId() != null && goodsQueryRequest.getMemberId() > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberId").as(Long.class), goodsQueryRequest.getMemberId()));
            }
            if (goodsQueryRequest.getMemberRoleId() != null && goodsQueryRequest.getMemberRoleId() > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberRoleId").as(Long.class), goodsQueryRequest.getMemberRoleId()));
            }
            if (goodsQueryRequest.getCustomerCategoryId() != null && goodsQueryRequest.getCustomerCategoryId() > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("customerCategory").as(CustomerCategory.class), goodsQueryRequest.getCustomerCategoryId()));
            }
            //内部状态筛选
            List<Integer> ids = goodsQueryRequest.getIds();
            List<Integer> externalStates = new ArrayList<>();//定义在MaterialsChangeOrEnableInternalStatusEnum code
            List<Integer> interiorStates = new ArrayList<>();//定义在MaterialsAddInternalStatusEnum code
            AtomicInteger count = new AtomicInteger();//统计99出现的次数
            ids.forEach(i -> {
                if (i > MaterialsAddInternalStatusEnum.FAILED_TO_PASS_THE_SECONDARY_AUDIT.getCode()) {
                    externalStates.add(i);
                } else {
                    interiorStates.add(i);
                }
                if (MaterialsAddInternalStatusEnum.CONFIRMED.getCode().equals(i)) {
                    count.getAndIncrement();
                }
            });
            if (count.get() == 2) {
                interiorStates.add(MaterialsAddInternalStatusEnum.CONFIRMED.getCode());
            }
            if (!CollectionUtils.isEmpty(interiorStates)) {
                Predicate interiorState = criteriaBuilder.and(root.get("interiorState").in(interiorStates));
                if (externalStates.size() > 1) {
                    Predicate or = criteriaBuilder.or(interiorState, criteriaBuilder.and(root.get("externalState").in(externalStates)));
                    finalConditions = criteriaBuilder.and(finalConditions, or);
                } else {
                    finalConditions = criteriaBuilder.and(finalConditions, interiorState);
                }
            }
            //因为工作流是动态的,所以必须保证 已确认 状态是在其中一个都成立
            if (externalStates.size() == 1 && Objects.equals(externalStates.get(0), MaterialsAddInternalStatusEnum.CONFIRMED.getCode())) {
                Predicate interiorState = criteriaBuilder.equal(root.get("interiorState"), MaterialsAddInternalStatusEnum.CONFIRMED.getCode());
                Predicate or = criteriaBuilder.or(interiorState, criteriaBuilder.equal(root.get("externalState"), MaterialsChangeOrEnableInternalStatusEnum.CONFIRMED.getCode()));
                finalConditions = criteriaBuilder.and(finalConditions, or);
            }
            if (externalStates.size() == 1 && !Objects.equals(externalStates.get(0), MaterialsAddInternalStatusEnum.CONFIRMED.getCode())) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("externalState"), externalStates.get(0)));
            }

            query.orderBy(criteriaBuilder.desc(root.get("createTime")));
            return finalConditions;
        };
    }


    /**
     * 构建查询条件
     *
     * @return 操作结果
     */
    private Specification<Goods> getAppSpecification(Long memberId, Long memberRoleId, String name) {
        return (root, query, criteriaBuilder) -> {
            Predicate finalConditions = criteriaBuilder.conjunction();
            if (!StringUtils.isEmpty(name)) {
                Predicate predicate = criteriaBuilder.or(criteriaBuilder.like(root.get("name").as(String.class), "%" + name + "%"), criteriaBuilder.like(root.get("code").as(String.class), "%" + name + "%"));
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.or(predicate, criteriaBuilder.like(root.get("brand").get("name").as(String.class), "%" + name + "%")));
            }
            if (memberId != null && memberId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberId").as(Long.class), memberId));
            }
            if (memberRoleId != null && memberRoleId > 0) {
                finalConditions = criteriaBuilder.and(finalConditions, criteriaBuilder.equal(root.get("memberRoleId").as(Long.class), memberRoleId));
            }
            query.orderBy(criteriaBuilder.desc(root.get("createTime")));
            return finalConditions;
        };
    }

    /**
     * 封装物料属性
     *
     * @param resultList 数据
     */
    @Override
    public void encapsulatedGoodsSubResponseData(List<GoodsSubResponse> resultList) {
        StringBuilder type = new StringBuilder();
        if (!CollectionUtils.isEmpty(resultList)) {
            resultList.forEach(goodsSubResponse -> {
                List<GoodsAttributeResponse> materialAttributeList = goodsSubResponse.getMaterialAttributeList();
                if (!CollectionUtils.isEmpty(materialAttributeList)) {
                    materialAttributeList.forEach(materialAttribute -> {
                        List<SimpleCustomerAttributeValueResponse> valueResponses = materialAttribute.getCustomerAttributeValueList();
                        if (!CollectionUtils.isEmpty(valueResponses)) {
                            valueResponses.forEach(v -> {
                                if (org.springframework.util.StringUtils.hasLength(v.getValue())) {
                                    type.append(v.getValue()).append("/");
                                }
                            });
                        }
                    });
                }
                if (type.length() > 0) {
                    goodsSubResponse.setType(type.substring(0, type.length() - 1));
                }
            });
        }
    }

    /**
     * 封装GoodsResponse物料属性
     *
     * @param resultList 数据
     */
    @Override
    public void encapsulatedGoodsResponseData(List<GoodsResponse> resultList) {
        StringBuilder type = new StringBuilder();
        if (!CollectionUtils.isEmpty(resultList)) {
            resultList.forEach(goodsSubResponse -> {
                List<GoodsAttributeResponse> materialAttributeList = goodsSubResponse.getMaterialAttributeList();
                if (!CollectionUtils.isEmpty(materialAttributeList)) {
                    materialAttributeList.forEach(materialAttribute -> {
                        List<SimpleCustomerAttributeValueResponse> valueResponses = materialAttribute.getCustomerAttributeValueList();
                        if (!CollectionUtils.isEmpty(valueResponses)) {
                            valueResponses.forEach(v -> {
                                if (org.springframework.util.StringUtils.hasLength(v.getValue())) {
                                    type.append(v.getValue()).append("/");
                                }
                            });
                        }
                    });
                }
                if (type.length() > 0) {
                    goodsSubResponse.setType(type.substring(0, type.length() - 1));
                }

            });
        }
    }

    /**
     * 物料管理-查询货品列表(同时返回生产厂家和产地)
     *
     * @param pageVO                  分页实体
     * @param goodsSourceQueryRequest 货品查询类
     * @return 操作结果
     */
    @Override
    public PageData<GoodsSourceResponse> getGoodsByMemberList(PageVO pageVO, UserLoginCacheDTO sysUser, GoodsSourceQueryRequest goodsSourceQueryRequest) {

        QGoods qGoods = QGoods.goods;
        QGoodsSupplyList qGoodsSupplyList = QGoodsSupplyList.goodsSupplyList;
        JPAQuery<Goods> query = jpaQueryFactory.select(qGoods)
                .from(qGoods).leftJoin(qGoodsSupplyList).on(qGoods.id.eq(qGoodsSupplyList.goods.id));
        //拼接查询条件
        BooleanBuilder builder = new BooleanBuilder();
        //条件为当前会员
        builder.and(qGoods.memberId.eq(sysUser.getMemberId())).and(qGoods.memberRoleId.eq(sysUser.getMemberRoleId()));

        if (StringUtils.isNotBlank(goodsSourceQueryRequest.getName())) {
            builder.and(qGoods.name.contains(goodsSourceQueryRequest.getName()));
        }
        if (StringUtils.isNotBlank(goodsSourceQueryRequest.getType())) {
            builder.and(qGoods.type.contains(goodsSourceQueryRequest.getType()));
        }
        if (StringUtils.isNotBlank(goodsSourceQueryRequest.getCode())) {
            builder.and(qGoods.code.eq(goodsSourceQueryRequest.getCode()));
        }
        if (goodsSourceQueryRequest.getBrandId() != null) {
            builder.and(qGoods.brand.id.eq(goodsSourceQueryRequest.getBrandId()));
        }
        if (goodsSourceQueryRequest.getCustomerCategoryId() != null) {
            builder.and(qGoods.customerCategory.id.eq(goodsSourceQueryRequest.getCustomerCategoryId()));
        }
        if (goodsSourceQueryRequest.getMaterialGroupId() != null) {
            builder.and(qGoods.materialGroup.id.eq(goodsSourceQueryRequest.getMaterialGroupId()));
        }
        //判断是否只看供应商可供物料
        if (goodsSourceQueryRequest.getWatch()) {
            if (goodsSourceQueryRequest.getMemberId() != null && goodsSourceQueryRequest.getMemberRoleId() != null) {
                builder.and(qGoodsSupplyList.memberId.eq(goodsSourceQueryRequest.getMemberId())).and(qGoodsSupplyList.memberRoleId.eq(goodsSourceQueryRequest.getMemberRoleId()).and(qGoodsSupplyList.status.eq(CommonBooleanEnum.YES.getCode())));
            }
        }
        //查询已完成的
        builder.and(qGoods.interiorState.eq(MaterialsAddInternalStatusEnum.CONFIRMED.getCode()).or(qGoods.externalState.eq(MaterialsChangeOrEnableInternalStatusEnum.CONFIRMED.getCode())));
        //分页排序
        query.where(builder).offset(pageVO.getCurrentOffset()).limit(pageVO.getPageSize()).orderBy(qGoods.createTime.desc());
        //获取总数
        long count = query.fetchCount();
        //获取查询结果
        List<Goods> goods = query.fetch();
        List<GoodsSourceResponse> responseList = new ArrayList<>();
        if (goods.size() > 0) {
            //数据转换
            responseList = goods.stream().map(good -> BeanUtil.copyProperties(good, GoodsSourceResponse.class)).collect(Collectors.toList());
            //封装unitName
            responseList.forEach(goodsSourceResponse -> {
                String unit = redisStringUtils.hMGet(Constants.REDIS_KEY_UNIT, String.valueOf(goodsSourceResponse.getUnitId()), Constants.REDIS_PLATFORM_MANAGE_INDEX);
                goodsSourceResponse.setUnitName(StringUtils.isNotEmpty(unit) ? unit.split(Constants.TRANSFER_STR + Constants.SPLIT_STR)[0] : "");
            });
            if (goodsSourceQueryRequest.getMemberId() != null && goodsSourceQueryRequest.getMemberRoleId() != null) {
                //获取全部物料id
                List<Long> goodsIds = responseList.stream().map(GoodsSourceResponse::getId).collect(Collectors.toList());
                //根据物料id和会员信息获取货源清单信息
                List<GoodsSupplyList> goodsSupplyLists = goodsSupplyListRepository.findByGoodsIdInAndMemberIdAndMemberRoleId(goodsIds, goodsSourceQueryRequest.getMemberId(), goodsSourceQueryRequest.getMemberRoleId());
                if (goodsSupplyLists.size() > 0) {
                    Map<Long, GoodsSupplyList> supplyListMap = goodsSupplyLists.stream().collect(Collectors.toMap(g -> g.getGoods().getId(), GoodsSupplyList -> GoodsSupplyList));
                    //封装数据
                    responseList = responseList.stream().peek(r -> {
                        GoodsSupplyList goodsSupplyList = supplyListMap.get(r.getId());
                        if (goodsSupplyList != null) {
                            r.setMemberId(goodsSupplyList.getMemberId());
                            r.setMemberRoleId(goodsSupplyList.getMemberRoleId());
                            r.setManufacturer(goodsSupplyList.getManufacturer());
                            r.setOrigin(goodsSupplyList.getOrigin());
                        }
                    }).collect(Collectors.toList());
                }
            }
        }
        return new PageData<>(count, responseList);
    }

    /**
     * 设置生产厂家和产地
     *
     * @param resultList 数据
     */
    @Override
    public void setGoodsResponseData(List<GoodsResponse> resultList, List<Goods> goodsList, UserLoginCacheDTO sysUser) {
        goodsList.forEach(goods -> {
            GoodsSupplyList goodsSupply = goods.getGoodsSupplyLists().stream().filter(o -> o.getMemberId().equals(sysUser.getMemberId())
                    && o.getMemberRoleId().equals(sysUser.getMemberRoleId()) && o.getGoods().getId().equals(goods.getId())).findFirst().orElse(null);
            GoodsResponse goodsResponse = resultList.stream().filter(result -> result.getId().equals(goods.getId())).findFirst().orElse(null);
            if (goodsSupply != null && goodsResponse != null) {
                goodsResponse.setManufacturer(goodsSupply.getManufacturer());
                goodsResponse.setOrigin(goodsSupply.getOrigin());
            }
        });
    }

    /**
     * 获取工作流信息
     *
     * @param goods   货品信息
     * @param sysUser 当前登录用户
     */
    @Override
    public void getProcessInfo(Goods goods, UserLoginCacheDTO sysUser, GoodsAndProcessResponse goodsResponse) {
        SimpleProcessDefResponse simpleProcessDefResponse = new SimpleProcessDefResponse();
        //动态获取工作流任务id
        Wrapper<MaterialProcessDTO> processDTOWrapper = materialProcessService.getMaterialProcessByMemberIdAndRoleIdAndMaterialGroupIdAndMaterialIdAndProcessType(sysUser.getMemberId(), sysUser.getMemberRoleId(), goods.getMaterialGroup() != null ? goods.getMaterialGroup().getId() : null, goods.getId(), MaterialProcessTypeEnum.CHANGE_OR_ENABLE.getCode());
        if (processDTOWrapper.getCode() != Wrapper.success().getCode()) {
            throw new BusinessException(processDTOWrapper.getCode(), processDTOWrapper.getMessage());
        }
        //封装工作流数据
        InternalProcessQueryVO queryVO = new InternalProcessQueryVO();
        queryVO.setProcessKey(goods.getProcessKey() != null ? goods.getProcessKey() : processDTOWrapper.getData().getProcessKey());
        queryVO.setMemberId(sysUser.getMemberId());
        queryVO.setTaskId(goods.getExternalTaskId() != null ? goods.getExternalTaskId() : goods.getInteriorTaskId());
        Wrapper<SimpleProcessDefVO> wrapper = taskExecuteControllerFeign.findSimpleInternalTaskDefinitions(queryVO);
        if (wrapper.getCode() != Wrapper.success().getCode()) {
            throw new BusinessException(wrapper.getCode(), wrapper.getMessage());
        }
        SimpleProcessDefVO vo = wrapper.getData();
        simpleProcessDefResponse.setCurrentStep(vo.getCurrentStep());
        simpleProcessDefResponse.setProcessName(vo.getProcessName());
        List<SimpleTaskVO> tasks = vo.getTasks();
        if (!CollectionUtils.isEmpty(tasks)) {
            simpleProcessDefResponse.setTasks(tasks.stream().map(t -> BeanUtil.copyProperties(t, SimpleTaskResponse.class)).collect(Collectors.toList()));
        }
        //处理特殊工作流状态
        if (MaterialsAddInternalStatusEnum.FROZEN.getCode().equals(simpleProcessDefResponse.getCurrentStep()) && simpleProcessDefResponse.getTasks().size() > 0) {
            SimpleTaskResponse simpleTaskResponse = simpleProcessDefResponse.getTasks().get(simpleProcessDefResponse.getTasks().size() - 1);
            if (simpleTaskResponse != null) {
                simpleProcessDefResponse.setCurrentStep(simpleTaskResponse.getTaskStep());
            }
        }
        goodsResponse.setSimpleProcessDefVO(simpleProcessDefResponse);
        //设置单位名称
        String unit = redisStringUtils.hMGet(Constants.REDIS_KEY_UNIT, String.valueOf(goods.getUnitId()), Constants.REDIS_PLATFORM_MANAGE_INDEX);
        goodsResponse.setUnitName(StringUtils.isNotEmpty(unit) ? unit.split(Constants.TRANSFER_STR + Constants.SPLIT_STR)[0] : "");
        //设置内部状态名称
        if (goods.getExternalState() != null && goods.getExternalState() > 0) {
            goodsResponse.setInteriorStateName(MaterialsChangeOrEnableInternalStatusEnum.getMessage(goods.getExternalState()));
            goodsResponse.setInteriorState(goods.getExternalState());
        } else {
            goodsResponse.setInteriorStateName(MaterialsAddInternalStatusEnum.getMessage(goods.getInteriorState()));
        }
    }
}


